<?php
namespace modules\org;
use \modules\auth\api as auth;
use \phiction\array_utils as arr;
use \phiction\exceptions\login as login_required;
use \phiction\exceptions\bad_request;

class api
{
    static function view($q, &$args)
    {
        $user = auth::validate($q, $args);
        $org  = $user['org'];
        $info = storage::info($q, $org)->run();
        if (is_null($info)) throw new login_required;
        return $info;
    }

    static function edit($q, &$args)
    {
        $name    = arr::get_or_bad_request($args, 'name');
        $comment = arr::get_or_bad_request($args, 'comment');

        $user = auth::validate_with_role($q, $args, 'admin');
        $org  = $user['org'];

        if (storage::edit($q, $org, $name, $comment)->run() !== 1)
            throw new bad_request("修改组织信息失败");
    }

    static function delete($q, &$args)
    {
        $password  = arr::get_or_bad_request($args, 'delete-password');
        $password2 = arr::get_or_bad_request($args, 'delete-password-again');
        if ($password !== $password2) throw new bad_request("两次密码不一致");

        $user = auth::validate_with_role($q, $args, 'admin');
        $org  = $user['org'];

        auth::validate_with_password($q, $args, $password);

        auth::logout($q, $args);
        if (storage::delete($q, $org)->run() !== 1)
            throw new bad_request("修改组织信息失败");
    }
}

